package com.stars.questions.deptQuestion.config.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stars.questions.deptQuestion.common.entity.CommonConstants;
import com.stars.questions.deptQuestion.config.entity.DeptConfigDTO;
import com.stars.questions.deptQuestion.config.entity.Organizes;
import com.stars.questions.deptQuestion.config.mapper.DeptMapper;
import com.stars.questions.deptQuestion.config.service.DeptService;
import com.stars.util.common.DevelopKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;


@Service
public class DeptServiceImpl implements DeptService {

    private final DeptMapper mapper;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public DeptServiceImpl(DeptMapper mapper) {
        this.mapper = mapper;
    }


    @Override
    public JSONObject getOrganizesList(DeptConfigDTO dto) {

        LambdaQueryWrapper<Organizes> query = new LambdaQueryWrapper<>();
        query.orderByAsc(Organizes::getShowOrder);

        JSONObject result = new JSONObject();
        logger.info("进入查询问卷部门列表方法，查询类别为：{}",dto.getType());

        if(CommonConstants.SELECT_ALL.equals(dto.getType())){

            Page<Organizes> page = Page.of(dto.getCurrent(), dto.getPageSize());

            query.like(Organizes::getOrgName, dto.getSearch());

            Page<Organizes> organizesPage = mapper.selectPage(page, query);

            //查询全部数据
            result.put("list",organizesPage.getRecords());
            result.put("total",organizesPage.getTotal());
            return result;
        }

        query.eq(Organizes::getStatus,1);

        result.put("list",mapper.selectList(query));
        return result;
    }

    @Override
    public Organizes getOrganizesData(String pk) {
        return mapper.selectById(pk);
    }

    @Override
    public boolean saveOrUpdate(Organizes org) {
        if(checkSaveOrUpdate(org)){
            org.setId(DevelopKit.generateUUID());
            DevelopKit.setBaseInfo(org);
            return mapper.insert(org) > 0;
        }

        org.setLastUpdateTime(new Date());
        return mapper.updateById(org) > 0;
    }

    @Override
    public boolean deleteData(String id) {
        return mapper.deleteById(id) > 0;
    }

    @Override
    public int getDeptMaxOrder() {
        Integer order = mapper.getDeptMaxOrder();

        if(order == null){
            return 1;
        }

        return order + 1;
    }

    private boolean checkSaveOrUpdate(Organizes org){
        if(!StringUtils.hasLength(org.getId())){
            return true;
        }
        Organizes temp = mapper.selectById(org.getId());
        return temp == null;
    }
}
